package com.whenjun.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ifootbook.util.FootBookException;
import com.ifootbook.util.MD5Util;
import com.ifootbook.util.PasswordUtil;
import com.whenjun.dto.login.PasswordUpdate;
import com.whenjun.entity.Account;
import com.whenjun.mapper.AccountMapper;
import com.whenjun.service.IAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author whenjun
 * @since 2023-11-08
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Autowired
    private AccessLogServiceImpl accessLogService;

    @Transactional
    public Account selectByName(String username) {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getUsername, username);
        wrapper.eq(Account::getStatus, false);

        Account account = getBaseMapper().selectOne(wrapper);
        return account;
    }

    @Transactional
    public Account selectByJobNo(String jobNo) {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getJobNo, jobNo);
        wrapper.eq(Account::getStatus, false);

        Account account = getBaseMapper().selectOne(wrapper);
        return account;
    }

    @Transactional
    public void updatePassword(PasswordUpdate passwordUpdate) {
        // 密码强度校验
        if (!PasswordUtil.validatePassword2(passwordUpdate.getPassword())){
            throw new FootBookException("密码必须为大写英文+小写+数字+特殊符号的组合");
        }

        String userId = (String) StpUtil.getLoginId();

        // 查询用户
        Account account = getBaseMapper().selectById(userId);

        String md5Pass = MD5Util.getMD5(passwordUpdate.getPassword());
        if(!md5Pass.equals(account.getPassword())) {
            throw new FootBookException("当前密码输入错误");
        }

        account.setPassword(MD5Util.getMD5(passwordUpdate.getNewPassword()));
        account.setUpdateTime(LocalDateTime.now());

        getBaseMapper().updateById(account);

        // 踢人下线
        StpUtil.kickout(userId);

        accessLogService.addLog(account.getUsername() + "修改了账户：" + account.getUsername() + "  的密码");
    }
}
